﻿using System;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using LuckyFish.ToDo.Data.Model;
using LuckyFish.ToDo.ViewModels;

namespace LuckyFish.ToDo.ToDoViews;

public partial class GroupView : UserControl
{
    public GroupView()
    {
        InitializeComponent();
        ToDoBox = this.FindControl<TextBox>("ToDoBox");
        Picker = this.FindControl<CalendarDatePicker>("Picker");
        TodoControl = this.FindControl<ContentControl>("TodoControl");
    }

    private void AddToDoClick(object? sender, RoutedEventArgs e)
    {
        if(string.IsNullOrEmpty(ToDoBox.Text) || Picker.SelectedDate == null)return;
        var todo = new ToDoModel()
        {
            CreateTime = DateTime.Now.ToString("g"),
            EndTime = Picker.SelectedDate.Value.ToString("d"),
            ToDoContext = ToDoBox.Text,
        };
        if(Parent?.DataContext is not MainWindowViewModel model)return;
        var Key = (DataContext as ToDoGroupModel)!.Key;
        model.Add(todo,Key);
    }

    private void SelectionTapped(object? sender, RoutedEventArgs e)
    {
        TodoControl.IsVisible = true;
        if(Parent?.DataContext is not MainWindowViewModel model)return;
        if(sender is not Control control)return;
        if(control.DataContext is not ToDoModel todo)return;
        TodoControl.Content = model.TodoLoad(todo);
    }

    private void TextKeyDown(object? sender, KeyEventArgs e)
    {
        if (e.Key != Key.Enter) return;
        if(DataContext is not ToDoGroupModel group)return;
        if(Parent?.DataContext is not MainWindowViewModel model)return;
        group.GroupName = (sender as TextBox)!.Text;
        model.Update(group);
    }
}